/**
 * UI动态渲染
 * varstion 1.0.1
 */

(function($) {
    var ms = {
        getVersion: "v0.0.0",
        configName: "",
        configDatas: null,
        init: function(data, cb) {
            if (data.config) {
                ms.configName = data.config;
                $.ajax('/load_file', {
                    data: {
                        "name": data.config
                    },
                    dataType: 'json', //服务器返回json格式数据
                    type: 'post', //HTTP请求类型
                    timeout: 10000, //超时时间设置为10秒；
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    success: function(evevt) {
                        if (evevt.success) {
                            ms.configDatas = evevt.data;
                            // alert(JSON.stringify(ms.configDatas))
                        } else {
                            ms.configDatas = {};
                        }
                        ms.renderUI(data, cb)
                    },
                    error: function(xhr, type, errorThrown) {
                        //异常处理；
                        alert("请求配置异常");
                        ms.renderUI(data, cb)
                    }
                });
            } else {
                if (ms.configName) {
                    function intervalChecks() {
                        if (ms.configDatas) {
                            ms.renderUI(data, cb);
                            clearInterval(intervalCheck);
                        }
                    }
                    var intervalCheck = setInterval(intervalChecks, 10)
                } else {
                    ms.renderUI(data, cb)
                }

            }
        },
        renderUI: function(data, cb) {
            var CLASS_TSTITLE = $.className('tstitle');
            var CLASS_TSCANCLE = $.className('tscancel');
            var CLASS_TSACTION = $.className('tsaction');
            var UiTile = $("." + CLASS_TSTITLE);
            var tsCancle = $("." + CLASS_TSCANCLE);
            var tsAction = $("." + CLASS_TSACTION);
            if (data.title) {
                UiTile[0].innerText = data.title;
            }
            if (data.cancelname) {
                tsCancle[0].innerText = data.cancelname;
            }
            if (data.okname) {
                tsAction[0].innerText = data.okname;
            }
            if (data.view && data.view.length > 0) {
                var ViveGroup = '';
                $.each(data.view, function(index, item) {
                    var componentType = item.type;
                    var listView = "";
                    var defultVal = item.select || item.text;
                    var comsNum = ms.comsNum(componentType);
                    switch (componentType) {
                        case "switches":
                            var switchesNameArr = ms.splitStr(item.list);
                            var itemAttrName = "" + comsNum.comNum;
                            if (item.id) {
                                itemAttrName = "val-" + item.id;
                            }
                            var selectVal = item.select;
                            if (ms.configDatas) {
                                if (ms.configDatas[itemAttrName] || ms.configDatas[itemAttrName] == "") {
                                    selectVal = ms.configDatas[itemAttrName];
                                }
                            }
                            var slectorArr = ms.splitStr(selectVal);
                            defultVal = selectVal;
                            $.each(switchesNameArr, function(index, val) {
                                var isIn = slectorArr.indexOf(index + "");
                                var isActive = "";
                                if (isIn > -1) {
                                    isActive = "mui-active";
                                }
                                listView += '\
                                <div class="mui-input-row">\
                                    <span class="mui-tslable">' + val + '</span>\
                                    <div class="mui-switch ' + isActive + '">\
                                        <div class="mui-switch-handle"></div>\
                                    </div>\
                                </div>';
                            });
                            break;
                        case "Image":
                            var imgSrc = item.src;
                            listView += '\
                            <div class="mui-tsimg"><img src=' + imgSrc + '></div>';
                            break;
                        case "RadioGroup":
                            var switchesNameArr = ms.splitStr(item.list);
                            var itemAttrName = "";

                            if (item.id) {
                                itemAttrName = "val-" + item.id;
                                var selectVal = item.select;
                                if (ms.configDatas) {
                                    if (ms.configDatas[itemAttrName] || ms.configDatas[itemAttrName] == "") {
                                        selectVal = ms.configDatas[itemAttrName];
                                    }
                                }
                                var slectorArr = ms.splitStr(selectVal);
                                defultVal = selectVal;

                                $.each(switchesNameArr, function(index, val) {
                                    var isIn = slectorArr.indexOf(index + "");
                                    var isChecked = "";
                                    if (isIn > -1) {
                                        isChecked = "checked";
                                    }
                                    listView += '\
                                <div class="mui-input-row mui-radio">\
                                    <label>' + val + '</label>\
                                    <input name="' + item.id + '" value="' + val + '" type="radio" ' + isChecked + '>\
                                </div>';
                                })
                            } else {
                                alert('请为"RadioGroup"组件添加id');
                            }

                            break;
                        case "CheckBoxGroup":
                            var switchesNameArr = ms.splitStr(item.list);
                            var itemAttrName = "";
                            if (item.id) {
                                itemAttrName = "val-" + item.id;
                                var selectVal = item.select;
                                if (ms.configDatas) {
                                    if (ms.configDatas[itemAttrName] || ms.configDatas[itemAttrName] == "") {
                                        selectVal = ms.configDatas[itemAttrName];
                                    }
                                }
                                var slectorArr = ms.splitStr(selectVal);
                                defultVal = selectVal;
                                $.each(switchesNameArr, function(index, val) {
                                    var isIn = slectorArr.indexOf(index + "");
                                    var isChecked = "";
                                    if (isIn > -1) {
                                        isChecked = "checked";
                                    }
                                    listView += '\
                                <div class="mui-input-row mui-checkbox">\
                                    <label>' + val + '</label>\
                                    <input name="' + item.id + '" value="' + val + '" type="checkbox" ' + isChecked + '>\
                                </div>';
                                })
                            } else {
                            alert('请为"CheckBoxGroup"组件添加id');
                            }

                            break;
                        case "ComboBox":
                            var switchesNameArr = ms.splitStr(item.list);
                            var secSlectlistArr = [];
                            var slectorArr = ms.splitStr(item.select);
                            var jsonData = "";
                            var comInitTxt = "";
                            var hasFind = false;
                            //获取组件独有id
                            var itemAttrName = "" + comsNum.comNum;
                            if (item.id) {
                                itemAttrName = "val-" + item.id;
                            }
                            //获取组件的默认值
                            var selectVal = item.select;
                            if (ms.configDatas) {
                                if (ms.configDatas[itemAttrName] || ms.configDatas[itemAttrName] == "") {
                                    selectVal = ms.configDatas[itemAttrName];
                                }
                            }

                            var selectValArr = ms.splitStr(selectVal, "#");
                            // var slectorArr = ms.splitStr(selectVal);
                            defultVal = selectVal;

                            if (item.data) {
                                hasFind = true;
                                $.each(switchesNameArr, function(index, val) {
                                    var secData = "";
                                    var secSlectArr = ms.splitStr(item.data, "#");
                                    secSlectlistArr = ms.splitStr(secSlectArr[index]);
                                    $.each(secSlectlistArr, function(index, val) {
                                        if (index == secSlectlistArr.length - 1) {
                                            secData += '{"text": "' + val + '"}';
                                        } else {
                                            secData += '{"text": "' + val + '"},';
                                        }

                                    });
                                    var secData = '[' + secData + ']';
                                    if (index == switchesNameArr.length - 1) {
                                        jsonData += '{"text": "' + val + '","children":' + secData + '}';
                                    } else {
                                        jsonData += '{"text": "' + val + '","children":' + secData + '},';
                                    }

                                })
                                jsonData = '[' + jsonData + ']';

                            } else {
                                $.each(switchesNameArr, function(index, val) {
                                    if (index == switchesNameArr.length - 1) {
                                        jsonData += '{"text": "' + val + '"}';
                                    } else {
                                        jsonData += '{"text": "' + val + '"},';
                                    }

                                })
                                jsonData = '[' + jsonData + ']';

                            }
                            var comDataArry = ms.toJson(jsonData);
                            ms.comboBoxObj[item.id] = comDataArry;
                            if (hasFind) {
                                var findVal = "";
                                if (selectValArr[1]) {
                                    findVal = comDataArry[selectValArr[0]].children[selectValArr[1]].text
                                } else {
                                    findVal = comDataArry[selectValArr[0]].children[0].text;
                                }
                                comInitTxt = comDataArry[selectValArr[0]].text + " . " + findVal;
                            } else {
                                comInitTxt = comDataArry[selectValArr[0]].text;
                            }
                            listView += '<button id="' + item.id + '" class="mui-btn mui-btn-block mui-tscombobox  mui-btn-blue mui-btn-sm" type="button">' + comInitTxt + '</button>';

                            break;
                        case "Label":
                            listView += '<h5 class="mui-content-padded" style="padding:5px 5px 0 5px;font-size:' + item.size + 'px;color:rgb(' + item.color + ');text-align:' + item.align + '">' + item.text + '</h5>';
                            break;
                        case "Edit":
                            //获取组件独有id
                            var itemAttrName = "" + comsNum.comNum;
                            if (item.id) {
                                itemAttrName = "val-" + item.id;
                            }
                            //获取组件的默认值
                            var selectVal = item.text;
                            if (ms.configDatas) {
                                if (ms.configDatas[itemAttrName] || ms.configDatas[itemAttrName] == "") {
                                    selectVal = ms.configDatas[itemAttrName];
                                }
                            }
                            defultVal=selectVal;
                            if (item.row) {
                                if (item.kbtype == "ascii") {
                                    listView += '<div class="mui-input-row"><textarea class="ts-textbox" rows="' + item.row + '" placeholder="' + item.prompt + '" type="text">' + selectVal + '</textarea></div>';
                                }
                            } else {
                                var inputType = '';
                                var classType = "mui-input-clear";
                                var isPsw = "";
                                var maxNum="";
                                var minNum="";
                                var placeholder = 'placeholder="' + item.prompt + '"';
                                if (item.kbtype == "ascii") {
                                    inputType = "text";
                                } else if (item.kbtype == "number") {
                                    inputType = "number";
                                } else if (item.kbtype == "password") {
                                    inputType = "password";
                                    isPsw = "mui-password";
                                    classType = "mui-input-password";
                                }else if(item.kbtype == "range"){
                                    inputType = "range";
                                    isPsw="mui-input-range";
                                    classType="";
                                    maxNum='max="'+item.max+'"';
                                    minNum='min="'+item.min+'"';
                                }
                                listView += '\
                                   <div class="mui-input-row ' + isPsw + '">\
                                        <input type="' + inputType + '" class="'+ classType + ' ts-textbox" ' + placeholder + ' value="' + selectVal + '" '+minNum+' '+maxNum+'>\
                                    </div>';

                            }
                            break;
                        default:
                            break;
                    }
                    var hasId = "";
                    if (item.id) {
                        hasId = 'id="val-' + item.id + '"';
                    }
                    if (comsNum.isCom) {
                        var pluginInput = '<input class="ts-valinput" data-comsnum="' + comsNum.comNum + '" type="hidden" ' + hasId + ' value="' + defultVal + '"/>';
                    }


                    if (listView) {
                        switch (item.type) {
                            case "RadioGroup":
                            case "CheckBoxGroup":
                            case "switches":
                                ViveGroup += '<div class="mui-input-group">' + listView + pluginInput + '</div>';
                                break;
                            case "ComboBox":
                            case "Edit":
                                ViveGroup += '<div class="mui-content-padded">' + listView + pluginInput + '</div>';
                                break;
                            default:
                                ViveGroup += listView;
                                break;
                        }
                    }

                });
                var box  =  document.createElement("div");
                box.innerHTML = ViveGroup;
                $("#renderbox")[0].appendChild(box);
                $.uiBind(ms.comboBoxObj);
                if (typeof(cb) == "function") {
                    cb();
                }
            }

        },
        comboBoxObj: {},
        comsNum: function(type) {
            var isCom = false;
            if (type == "switches" || type == "RadioGroup" || type == "Edit" || type == "CheckBoxGroup" || type == "ComboBox") {
                ms.comSequential += 1;
                isCom = true;
            }
            return {
                "comNum": ms.comSequential,
                "isCom": isCom
            };
        },
        comSequential: -1,
        splitStr: function(str, symb) { //数组转换
            var arrList = []
            if (symb) {
                arrList = str.split(symb);
            } else {
                arrList = str.split(/[,@]/g);
            }
            return arrList;
        },
        toJson: function(str) {
            return JSON.parse(str);
        },
    }
    $.configName = function() {
        return ms.configName;
    }
    $.getVersion = function() {
        return ms.getVersion;
    }
    $.renderUI = function(data, cb) {
        ms.init(data, cb)
    }
})(mui);